package com.example.wln;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.URLEncoder;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.StrKit;

public class WanlnService {

	public static String getToken(List<Parameter> parameters, String serverSecret) throws IOException {

		if (parameters == null || parameters.size() == 0 || StrKit.isBlank(serverSecret)) {
			throw new IllegalArgumentException();
		}

		Collections.sort(parameters);

		StringBuffer sb = new StringBuffer(serverSecret);
		for (Parameter parameter : parameters) {
			if (!parameter.getKey().equals("sign")) {
				sb.append(parameter.getKey()).append(parameter.getValue());
			}
		}
		sb.append(serverSecret);
		System.out.println("签名前："+sb.toString());
		return byte2hex(encryptMD5(sb.toString()));
	}

	private static String getStringFromException(Throwable e) {
		String result = "";
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		PrintStream ps = new PrintStream(bos);
		e.printStackTrace(ps);
		try {
			result = bos.toString(CHARSET_UTF8);
		} catch (IOException ioe) {
		}
		return result;
	}

	private static byte[] encryptMD5(String data) throws IOException {
		byte[] bytes = null;
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			bytes = md.digest(data.getBytes(CHARSET_UTF8));
		} catch (GeneralSecurityException gse) {
			String msg = getStringFromException(gse);
			throw new IOException(msg);
		}
		return bytes;
	}

	private static String byte2hex(byte[] bytes) {
		StringBuilder sign = new StringBuilder();
		for (int i = 0; i < bytes.length; i++) {
			String hex = Integer.toHexString(bytes[i] & 0xFF);
			if (hex.length() == 1) {
				sign.append("0");
			}
			sign.append(hex.toUpperCase());
		}
		return sign.toString();
	}

	public static String md5(String source) throws IOException {
		return byte2hex(encryptMD5(source));
	}

	public static final String CHARSET_UTF8 = "UTF-8";

	public static void main(String[] args) {
		List<Parameter> parameters = new ArrayList<Parameter>();
		Parameter para = new Parameter("app_key", WanlnConfig.appKey);
		parameters.add(para);
		para = new Parameter("format", "json");
		parameters.add(para);
		para = new Parameter("timestamp", String.valueOf(new Date().getTime()));
		parameters.add(para);

		// categories
		JSONArray jsonArray = new JSONArray();
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("shopNick", WanlnConfig.shopNick);
		jsonObject.put("categoryID", "001");
		jsonObject.put("name", "testcategroy");
		jsonObject.put("parentID", "");
		jsonObject.put("status", 1);
		jsonObject.put("sortOrder", 1);
		jsonArray.add(jsonObject);
		String categories = URLEncoder.encode(jsonArray.toString());
		para = new Parameter("categories", categories);
		parameters.add(para);
		String sign = "";
		try {
			sign = getToken(parameters, WanlnConfig.appSecret);
			para = new Parameter("sign", sign);
			parameters.add(para);
		} catch (IOException e) {
			e.printStackTrace();
		}

		String paramsJson = JsonKit.toJson(parameters);

		Map<String, String> headers = new HashMap<String, String>();
		headers.put("Content-Type", "application/x-www-form-urlencoded");
		String result = HttpKit.post(WanlnConfig.testWanlnUrl + WanlnConfig.version + WanlnConfig.categoryApi
				+ "/?app_key=" + WanlnConfig.appKey + "&timestamp=" + String.valueOf(new Date().getTime())
				+ "&format=json" + "&sign=" + sign + "&categories=" + URLEncoder.encode(jsonArray.toString()), "",
				headers);
		System.out.println("result:" + result);

	}

}
